package com.yawn.zerodefect.util.thread;

import java.util.concurrent.*;

/**
 * @author yawn
 * @date 2018-03-13 11:37
 */
public class ThreadUtil {

    private ThreadUtil() {
    }

    /**
     * 开启线程执行Callable，并返回结果
     * @param callable 需要执行的实现类
     * @param <V> 返回结果类型
     */
    public static <V> V executeCallable(Callable<V> callable) throws ExecutionException, InterruptedException {
        FutureTask<V> futureTask = new FutureTask(callable);
        new Thread(futureTask).start();
        return futureTask.get();
    }

    /**
     * 开启线程执行Runnable
     * @param runnable 需要执行的实现类
     */
    public static void executeRunnable(Runnable runnable) {
        new Thread(runnable).start();
    }


    public static ExecutorService getCachePool() {
        return Executors.newCachedThreadPool();
    }

    public static void poolExecute(Runnable runnable) {
        ExecutorService pool = getCachePool();
        pool.submit(runnable);
    }

    public static  <V> V poolExecute(Callable<V> callable) {
        ExecutorService pool = getCachePool();
        Future<V> future = pool.submit(callable);
        V result = null;
        try {
            result = future.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
